<?php

namespace app\api\controller;

use think\Controller;
use Classes\PHPExcel_IOFactory;
use Classes\PHPExcel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class FileHandle extends Controller {
    /**
     * 读取Excel - Logic
     * @param $filePath 文件路径
     * @param $suffix 文件后缀 xls/xlsx
     * @param $type 处理类型 0-敏感词
     */
    public static function readExcel($filePath, $suffix, $type) {
        //判断哪种类型
        if($suffix=="xlsx"){
            $reader = \PHPExcel_IOFactory::createReader('Excel2007');
        }else{
            $reader = \PHPExcel_IOFactory::createReader('Excel5');
        }
        //载入excel文件
        $excel = $reader->load("$filePath",$encode = 'utf-8');
        //读取第一张表
        $sheet = $excel->getSheet(0);
        //获取总行数
        $row_num = $sheet->getHighestRow();
        //获取总列数
        $col_num = $sheet->getHighestColumn();
        
        switch ($type) {
            case '0':
                $sensitiveArr = [];
                for ($i = 1; $i <= $row_num; $i ++) {
                    $word = $sheet->getCell("A".$i)->getValue();
                    array_push($sensitiveArr, $word);
                }
                return operationRes(true, 'Handle Read Excel Successful', ['res' => $sensitiveArr]);
                break;
            
            default:
                return operationRes(false, 'Handle Read Excel Failed');
                break;
        }
    }

    /**
     * 导出Excel - Logic
     * @param $obj 数据对象
     * @param $type 处理类型 0-敏感词
     */
    public static function exportExcel($obj, $type) {
        $spreadsheet = new Spreadsheet();
        $sheel = $spreadsheet->getActiveSheet();

        $fileFolder = '/';
        $fileName = '默认';
        
        switch ($type) {
            case '0':
                $fileName = $obj['fileName'];
                $fileFolder = $obj['fileFolder'];
                foreach ($obj['list'] as $key => $val) {
                    $sheel->setCellValue('A'.($key+1), $val['name']);
                }
                break;
            
            default:
                return operationRes(false, 'Handle Export Excel Failed');
                break;
        }
        
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx"');
        header('Cache-Control: max-age=0');
        $writer = new Xlsx($spreadsheet);
        $filePath = $fileFolder.$fileName.'.xlsx';
        $path = ROOT_PATH.$filePath;
        $writer->save($path);
        return operationRes(true, 'Handle Export Excel Successful', ['res' => $filePath]);
    }
}
